#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<bitset>
#include<vector>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define rep(i,a,b) for(register int i = (a);i <= (b);++i)
#define per(i,a,b) for(register int i = (a);i >= (b);--i)  
typedef long long ll;
typedef unsigned long long ull;
using std::string;using std::cin;using std::cout;

const int N = 5e6+1e3;
int n,m,t[N],l,r,q[N];
ll cnt[N],sum[N],dp[N];

inline bool cmp(int x,int y){return x < y;}

//无斜率优化
int main(){
    std::ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    //freopen("in.in", "r", stdin);
    cin >> n >> m;
    rep(i,1,n){
        cin >> t[i];
        sum[ t[i] ] += t[i] , ++cnt[ t[i] ];
    }
    std::sort(t+1,t+n+1,cmp);
    rep(i,1,t[n]+m-1) sum[i] += sum[i-1] , cnt[i] += cnt[i-1];
    rep(i,1,t[n]+m-1){
        if(i > m) if(cnt[i-m] == cnt[i]){dp[i] = dp[i-m];continue;}
        dp[i] = cnt[i] * i - sum[i];
        rep(j,std::max(i-2*m+1,0),i-m) dp[i] = std::min(dp[i],dp[j] + (cnt[i]-cnt[j])*i - (sum[i]-sum[j]));
    }
    ll ans = 1e9+9;
    rep(i,t[n],t[n]+m-1) ans = std::min(ans,dp[i]);
    cout << ans << "\n";
    return 0;
}